import React, { useEffect, useState } from 'react';
import {
  Form,
  Input,
  Select,
  Card,
  Button,
  DatePicker as datePicker,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { FormItemRenderBox } from '../FormItemRender';
import { editParticipantsList } from '@/pages/DarkPleaseCloseYourEyes/services';
// 解决ts类型报错
const DatePicker: any = datePicker;
const { Option } = Select;
import './style.less';

// 表单配置
export type IFormItemType = {
  type: 'select' | 'input';
  key: string;
  name: string;
  label: string;
  placeholder?: string;
  span?: number;
  offset?: number;
  pull?: number;
  labelCol?: { span?: number; offset?: number; pull?: number };
  // label提示
  tips?: string;
  // 下拉列表数据
  selectList?: any[];
  // Col类名
  className?: string;
  // 互斥列表key
  mutexKeyList?: string[];
};

export type IFormItemRenderBox = (props: {
  item: IFormItemType;
  index?: number;
  form?: any;
  // 参与人员
  participantsList?: any[];
  // 修改参与人员
  setParticipantsList?: any;
  // 数据同步座位表
  dayListChange?: any;
  // 终止渲染
  not?: boolean;
  // 自定义渲染
  children?: React.FC;
}) => any;

export type IFormItemMapType = {
  [key: string]: IFormItemRenderBox;
};

// 根据类型渲染
export const FormItemMap: IFormItemMapType = {
  // 文本输入框
  input: ({ item }) => {
    const { placeholder } = item;
    return <Input placeholder={placeholder}></Input>;
  },
  // 下拉
  select: ({ item }) => {
    const { placeholder, selectList = [] } = item;
    return (
      <Select allowClear placeholder={placeholder}>
        {selectList.map((item) => {
          return (
            <Option key={item.key} value={item.key}>
              {item.label}
            </Option>
          );
        })}
      </Select>
    );
  },
  // 多选下拉
  multipleSelect: ({ item, participantsList = [], form }) => {
    const { placeholder, mutexKeyList } = item;
    const disableList: string[] = [];

    // 互斥禁用
    if (mutexKeyList) {
      mutexKeyList
        .map((mutexKey) => form.getFieldValue(mutexKey))
        .reduce((arr, item) => {
          if (item) {
            arr.push(...item);
          }
          return arr;
        }, [])
        .forEach((item: any) => {
          disableList.push(item);
        });
    }

    return (
      <Select allowClear mode="multiple" placeholder={placeholder}>
        {participantsList.map((item) => {
          return (
            <Option
              key={item.key}
              value={item.key}
              disabled={disableList.includes(item.key)}
            >
              {item.key + '号' + item.label}
            </Option>
          );
        })}
      </Select>
    );
  },
  // 日期选择器
  datePicker: () => <DatePicker showTime />,
  // 参与人员
  participantsListSelect: ({ item, setParticipantsList }) => {
    const { placeholder, selectList = [] } = item;
    return (
      <Select
        allowClear
        mode="multiple"
        placeholder={placeholder}
        onChange={(e) => {
          editParticipantsList(e);
          setParticipantsList(
            e.map((item: any, index: any) => {
              return {
                key: index + 1,
                label: item,
              };
            }),
          );
        }}
      >
        {selectList.map((items) => {
          return (
            <Option key={items.key} value={items.key}>
              {items.label}
            </Option>
          );
        })}
      </Select>
    );
  },
};

// 根据key渲染
export const CustomItemMap: IFormItemMapType = {
  // 每天进度
  dayList: ({ participantsList = [], form, item }) => {
    const { mutexKeyList = [] } = item;
    return (
      <div style={{ width: 500, margin: '0 20px 0 50px' }}>
        <Form.List name="dayList">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }) => {
                const list = form.getFieldValue('dayList');
                // 可杀,投
                const disabledList: string[] = [];
                // 可查验
                const checkDisableList: string[] = [];
                list?.forEach((obj: any, index: number) => {
                  mutexKeyList.forEach((key) => {
                    if (obj?.[key]) {
                      disabledList.push(obj[key]);
                      if (index !== list.length - 1) {
                        checkDisableList.push(obj[key]);
                      }
                    }
                  });
                });

                return (
                  <Card key={name} style={{ width: '100%', marginBottom: 20 }}>
                    <div style={{ marginBottom: 20 }}>
                      {name === fields.length - 1 && (
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      )}
                      <span
                        style={{
                          marginLeft: name === fields.length - 1 ? 60 : 74,
                        }}
                      >
                        第 {name + 1} 天 夜 晚
                      </span>
                    </div>
                    <Form.Item
                      {...restField}
                      name={[name, 'killNum']}
                      label="被刀"
                    >
                      <Select allowClear placeholder="请选择">
                        {participantsList.map((item: any) => {
                          return (
                            <Option
                              key={item.key}
                              value={item.key}
                              disabled={disabledList.includes(item.key)}
                            >
                              {item.key + '号' + item.label}
                            </Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'checkNum']}
                      label="查验"
                    >
                      <Select allowClear placeholder="请选择">
                        {participantsList.map((item: any) => {
                          return (
                            <Option
                              key={item.key}
                              value={item.key}
                              disabled={checkDisableList.includes(item.key)}
                            >
                              {item.key + '号' + item.label}
                            </Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                    <div style={{ marginBottom: 20 }}>
                      <span style={{ marginLeft: 74 }}>
                        第 {name + 1} 天 白 天
                      </span>
                    </div>
                    <Form.Item
                      {...restField}
                      name={[name, 'throw']}
                      label="公投"
                    >
                      <Select allowClear placeholder="请选择">
                        {participantsList.map((item: any) => {
                          return (
                            <Option
                              key={item.key}
                              value={item.key}
                              disabled={disabledList.includes(item.key)}
                            >
                              {item.key + '号' + item.label}
                            </Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                  </Card>
                );
              })}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  增加天数
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </div>
    );
  },
  // 平民阵营
  civilianList: (formItemConfig) => {
    const { item, form, participantsList = [], dayListChange } = formItemConfig;
    const { mutexKeyList = [] } = item;
    const dependKey = Form.useWatch(item.key, form);

    useEffect(() => {
      dayListChange(form.getFieldsValue(true));
    }, [dependKey]);
    const onClick = () => {
      const mutexKey = mutexKeyList
        .map((item) => form.getFieldValue(item))
        .reduce((arr, item) => {
          if (item) {
            arr.push(...item);
          }
          return arr;
        }, []);

      const filterPeople = participantsList
        .filter((item) => {
          return !mutexKey.includes(item.key);
        })
        .map((item) => item.key);
      form.setFieldValue(item.key, filterPeople);
      form.validateFields([item.key]);
      //
    };
    return (
      <div className="civilianList">
        <FormItemRenderBox {...formItemConfig} not>
          {FormItemMap[formItemConfig.item.type](formItemConfig)}
        </FormItemRenderBox>
        <div className="extra">
          <Button type="primary" onClick={onClick}>
            点击自动填入剩余人员
          </Button>
        </div>
      </div>
    );
  },
};
